package com.pactera.asmp.server.restfullapi;

import com.alibaba.fastjson.JSONObject;
import com.pactera.asmp.server.common.annotations.JwtIgnore;
import com.pactera.asmp.server.common.constants.ResultCode;
import com.pactera.asmp.server.entity.AutoTestTaskExecDTO;
import com.pactera.asmp.server.entity.MasterComputerDTO;
import com.pactera.asmp.server.entity.ResponseResult;
import com.pactera.asmp.server.entity.TaskDataDTO;
import com.pactera.asmp.server.entity.TaskExecDTO;
import com.pactera.asmp.server.entity.TaskProcessDTO;
import com.pactera.asmp.server.job.dispatch.impl.feedback.FeedbackManager;
import com.pactera.asmp.server.pojo.DeviceInfo;
import com.pactera.asmp.server.pojo.Issue;
import com.pactera.asmp.server.service.DeviceServiceImpl;
import com.pactera.asmp.server.service.IFileParseService;
import com.pactera.asmp.server.service.IProjectDeviceDbcService;
import com.pactera.asmp.server.service.IssueService;
import com.pactera.asmp.server.service.MasterComputerServiceImpl;
import com.pactera.asmp.server.service.TaskService;

import com.pactera.asmp.server.vo.TerminalPerformanceInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/terminal/api/v1")
public class RestfulTerminalApi {

    private static final Logger logger = LoggerFactory.getLogger(RestfulTerminalApi.class);

    @Autowired
    private TaskService taskService;

    @Autowired
    private MasterComputerServiceImpl mMasterComputerService;

    @Autowired
    private DeviceServiceImpl mDeviceServiceImpl;

    @Autowired
    private IssueService issueService;

    @Autowired
    private IProjectDeviceDbcService projectDeviceDbcService;

    @Autowired
    private IFileParseService fileParseService;

    // 任务执行时调用
    @PutMapping(value = "/taskStart", produces = "application/json;charset=UTF-8")
    public ResponseResult taskStart(@RequestBody @Validated TaskExecDTO taskExecDTO) {
        logger.info("PUT /terminal/api/v1/task/taskStart");
        ResponseResult responseResult = taskService.execTask(taskExecDTO);
//        taskService.taskChangedAfterStartTask(taskExecDTO);
        return responseResult;
    }

    @Autowired
    private FeedbackManager feedbackManager;

    @PostMapping(value = "/taskOffline", produces = "application/json;charset=UTF-8")
    public ResponseResult offlineMock(@RequestBody @Validated TaskExecDTO taskExecDTO) {
        logger.info("PUT /terminal/api/v1/task/taskOffline");
        feedbackManager.feedbackForDeviceOfflineMock(taskExecDTO.getDuid());
        return ResponseResult.defaultSuccess(null);
    }

    @PostMapping(value = "/taskComplete", produces = "application/json;charset=UTF-8")
    public ResponseResult taskComplete(@RequestBody @Validated TaskDataDTO taskDataDTO) {
        logger.info("POST /terminal/api/v1/task/taskComplete: {}",taskDataDTO.getTask().getId());
        return taskService.taskComplete(taskDataDTO);
    }

    @PostMapping(value = "/taskProcess", produces = "application/json;charset=UTF-8")
    public ResponseResult taskProcess(@RequestBody TaskProcessDTO taskProcessDTO) {
        return taskService.taskProcess(taskProcessDTO);
    }

    @PostMapping(value = "/device-offline", produces = "application/json;charset=UTF-8")
    public ResponseResult deviceOffline(@RequestBody DeviceInfo deviceInfo) {
        return mDeviceServiceImpl.handleDeviceOffline(deviceInfo);
    }

    //    // 注册上位机url
    @PostMapping(value = "/masterc", produces = "application/json;charset=UTF-8")
    @JwtIgnore
    public ResponseResult registerMasterComputer(@RequestBody MasterComputerDTO masterComputerDTO) {
        logger.info("POST /terminal/api/v1/masterc registerMasterComputer");
        return mMasterComputerService.registerMasterComputer(masterComputerDTO);
    }

    //    // 注册手机设备url
    @PostMapping(value = "/device",produces = "application/json;charset=UTF-8")
    public ResponseResult registerDevice(@RequestBody DeviceInfo deviceInfo) {
        logger.info("POST /terminal/api/v1/devcie registerDevice");
//        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//        logger.info("注册设备 : {}------{}",request.getRemoteHost(),request.getRemoteAddr());
        return mDeviceServiceImpl.registerDevice(deviceInfo);
    }


    @PostMapping("/issue")
    @JwtIgnore
    public ResponseResult issue(@RequestBody Issue issue){
        logger.info("POST /terminal/api/v1/issue");
        return ResponseResult.defaultSuccess(this.issueService.addIssue(issue));
    }

    @PostMapping("/report-performance")
    public ResponseResult reportPerformance(@RequestBody TerminalPerformanceInfo tpInfo){
        logger.info("POST /terminal/api/v1/report-performance");
        return taskService.reportPerformance(tpInfo);
    }

    // fix Sprint5 T022
    @PostMapping(value = "/simulator/status",produces = "application/json;charset=UTF-8")
    public ResponseResult operationDevice(@RequestBody JSONObject params) {
        String duid = params.getString("duid");
        Integer userId = 999999;  // 常量，代码Simulator设备
        Integer status = params.getInteger("status");   // 1 申请占用   0 空闲    2 断线
        String userName = params.getString("simulatorId"); // 传Simulator对应的唯一ID，一个Simulator同一时间只能占用一个设备
        logger.info("/terminal/api/v1/simulator/status  duid :{}, userId:{}, status:{} , userName {}",duid,userId,status,userName);
        ResponseResult responseResult;
        if(StringUtils.isEmpty(duid) || status == null || StringUtils.isEmpty(userName)){
            responseResult = new ResponseResult(ResultCode.PARAM_IS_BLANK);
            return responseResult;
        }
        return mDeviceServiceImpl.operationDeviceForSimulator(duid,userId, status, userName) ? new ResponseResult(ResultCode.SUCCESS) : new ResponseResult(ResultCode.BUSINESS_DEVICE_OPER_ERR);
    }

    // fix Sprint5 T022
    @PostMapping(value = "/simulator/online",produces = "application/json;charset=UTF-8")
    public ResponseResult onlineDuidSimulator(@RequestBody JSONObject params) {
        logger.info("POST /terminal/api/v1/simulator/online");
        String duid = params.getString("duid");
        String simulatorId = params.getString("simulatorId"); // 传Simulator对应的唯一ID，一个Simulator同一时间只能占用一个设备
        mDeviceServiceImpl.onlineDuidSimulator(duid,simulatorId);
        return ResponseResult.defaultSuccess(null);
    }

    /**
     * @api {GET} /api/v1/proDevice/queryProjectAndDbcByDuid queryProjectAndDbcByDuid
     * @apiVersion 1.0.0
     * @apiGroup RestfulProjectDeviceDbcApi
     * @apiName queryProjectAndDbcByDuid
     * @apiDescription 根据 duid 获取对应已绑定项目名和dbc名 (simulator端需根据duid获取项目及dbc解析文件)
     * @apiParam (请求参数) {String} duid 设备duid
     * @apiParamExample 请求参数示例
     * duid=DsHp8
     * @apiSuccess (响应结果) {Number} code
     * @apiSuccess (响应结果) {String} message
     * @apiSuccess (响应结果) {Object} data
     * @apiSuccessExample 响应结果示例
     * {"code":5461,"data":{},"message":"LCNFLzs"}
     */
    @GetMapping("/proDevice/queryProjectAndDbcByDuid")
    public ResponseResult queryProjectAndDbcByDuid(String duid) {
        logger.info("/terminal/api/v1/proDevice/queryProjectAndDbcByDuid duid: {}", duid);
        if (StringUtils.isEmpty(duid)) {
            return new ResponseResult(ResultCode.PARAM_IS_BLANK);
        }
        ResponseResult responseResult = new ResponseResult(ResultCode.SUCCESS);
        responseResult.setData(projectDeviceDbcService.queryProjectAndDbcByDuid(duid));
        return responseResult;
    }


    /**
     * @api {GET} /terminal/api/v1/devicesByCuid getDevicesByCuid
     * @apiVersion 1.0.0
     * @apiGroup RestfulTerminalApi
     * @apiName getDevicesByCuid
     * @apiDescription 根据上位机CUID获取设备列表
     * @apiParam (请求参数) {String} cuid 上位机CUID
     * @apiParamExample 请求参数示例
     * cuid=xxxxxxx
     * @apiHeader {String} Authorization Bearer xxx
     * @apiHeaderExample {json} 请求头样例:
     * { "Authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1dWlkIjoiNTAiLCJjaGFubmVsSWQiOjUsInJvbGVJZCI6IjIiLCJjcmVhdGVUaW1lIjoxNjE1MzU5MDgxNDY1LCJsb2NhbGhvc3QiOiJCQUIxOTAwMjE1Iiwic3ViIjoiYWRtaW4iLCJpc3MiOiIyZDBhNDI2MTY5MjYwYzA4NmIxNWU4MzlhYmEyMGUwOSIsImlhdCI6MTYxNTM1OTA4MSwiYXVkIjoicmVzdGFwaXVzZXIiLCJleHAiOjE2MTc5NTEwODEsIm5iZiI6MTYxNTM1OTA4MX0.BpUVtIE4kWyWKD8-b7lAv1611rv5N1U1q0VO4ijD0P0" }
     * @apiSuccess (响应结果) {Number} code
     * @apiSuccess (响应结果) {String} message
     * @apiSuccess (响应结果) {Object} data
     * @apiSuccessExample 响应结果示例
     * {"code":7758,"data":{},"message":"mNxF1axK"}
     */
    @GetMapping("/devicesByCuid")
    public ResponseResult getDevicesByCuid(String cuid){
        logger.info("/terminal/api/v1/devicesByCuid cuid: {}", cuid);
        return ResponseResult.defaultSuccess(mDeviceServiceImpl.getDevicesByCuid(cuid));
    }


    /**
     * @api {GET} /terminal/api/v1/proDevice/prodbc getProdbcList
     * @apiVersion 1.0.0
     * @apiGroup RestfulProjectDeviceDbcApi
     * @apiName projectDeviceList2
     * @apiDescription 根据设备ID查询可用的项目DBC文件
     * @apiParam (请求参数) {Number} projectId 项目ID
     * @apiParam (请求参数) {Number} deviceId 设备ID
     * @apiParam (请求参数) {String} duid 设备号
     * @apiParamExample 请求参数示例
     * projectId=2877&deviceId=1098
     * @apiHeader {String} Authorization Bearer xxx
     * @apiHeaderExample {json} 请求头样例:
     * { "Authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1dWlkIjoiNTAiLCJjaGFubmVsSWQiOjUsInJvbGVJZCI6IjIiLCJjcmVhdGVUaW1lIjoxNjE1MzU5MDgxNDY1LCJsb2NhbGhvc3QiOiJCQUIxOTAwMjE1Iiwic3ViIjoiYWRtaW4iLCJpc3MiOiIyZDBhNDI2MTY5MjYwYzA4NmIxNWU4MzlhYmEyMGUwOSIsImlhdCI6MTYxNTM1OTA4MSwiYXVkIjoicmVzdGFwaXVzZXIiLCJleHAiOjE2MTc5NTEwODEsIm5iZiI6MTYxNTM1OTA4MX0.BpUVtIE4kWyWKD8-b7lAv1611rv5N1U1q0VO4ijD0P0" }
     * @apiSuccess (响应结果) {Number} code
     * @apiSuccess (响应结果) {String} message
     * @apiSuccess (响应结果) {Object} data
     * @apiSuccessExample 响应结果示例
     * {"code":1565,"data":{},"message":"lQus"}
     */
    @GetMapping("/proDevice/prodbc")
    public ResponseResult getProdbcList(Integer projectId, Integer deviceId,String duid) {
        logger.info("/terminal/api/v1/proDevice/prodbc projectId: {}, deviceId: {}, duid: {}", projectId, deviceId,duid);
        ResponseResult responseResult = new ResponseResult(ResultCode.SUCCESS);
        responseResult.setData(projectDeviceDbcService.selective2(projectId, deviceId,duid));
        return responseResult;
    }


    /**
     * @api {GET} /terminal/api/v1/dbc/getDbc getDbc
     * @apiVersion 1.0.0
     * @apiGroup RestfullFileUploadApi
     * @apiName getDbc
     * @apiDescription 根据主键获取 dbc 解析后的文件
     * @apiParam (请求参数) {Number} dbcId dbc主键
     * @apiParamExample 请求参数示例
     * dbcId=6748
     * @apiSuccess (响应结果) {Number} code
     * @apiSuccess (响应结果) {String} message
     * @apiSuccess (响应结果) {Object} data
     * @apiSuccessExample 响应结果示例
     * {"code":6971,"data":{},"message":"HVqiMu"}
     */
    @GetMapping("/dbc/getDbc")
//    public ResponseResult getDbc(Long dbcId,@RequestParam(value = "simple",defaultValue = "false",required = false) Boolean simpleFormatter) {
    public ResponseResult getDbc(Long dbcId) {
//        logger.info("/terminal/api/v1/dbc/getDbc dbcId: {},{}", dbcId,simpleFormatter);
        logger.info("/terminal/api/v1/dbc/getDbc dbcId: {}", dbcId);
        ResponseResult responseResult;
        if (null == dbcId || 0 == dbcId) {
            responseResult = new ResponseResult(ResultCode.PARAM_IS_BLANK);
            return responseResult;
        }
        responseResult = new ResponseResult(ResultCode.SUCCESS);
        responseResult.setData(fileParseService.getDbcParse(dbcId));
        return responseResult;
    }

    @GetMapping("/license/auth")
    public ResponseResult getLicenseAuthResult(String auid) {
        logger.info("/license/auth, auid: {}",auid);
        ResponseResult responseResult = new ResponseResult(ResultCode.SUCCESS);
        responseResult.setData(null);
        return responseResult;
    }

    @PostMapping("/production/autotesttask/create")
    public ResponseResult createAutoTestTask(@RequestBody AutoTestTaskExecDTO autoTestTaskExecDTO) throws Exception {
        logger.info("/production/autotesttask/create, autoTestTaskExecDTO: {}", JSONObject.toJSONString(autoTestTaskExecDTO));
        if (null == autoTestTaskExecDTO.getProductionLineHistoryId()
                || null == autoTestTaskExecDTO.getMasterComputerId()
                || StringUtils.isEmpty(autoTestTaskExecDTO.getApkName())) {
            return new ResponseResult(ResultCode.PARAM_IS_BLANK);
        }
        return taskService.createAutoTestTask(autoTestTaskExecDTO);
    }
}
